package com.example.jasper.controller;

import com.example.jasper.dto.User;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;

@RestController
public class JasperController {
    @GetMapping("/testJasper")
    public void createPdf(HttpServletResponse response, HttpServletRequest
            request) throws Exception {
        //引入jasper文件。由JRXML模板编译生成的二进制文件，用于代码填充数据
        Resource resource = new ClassPathResource("templates/test01.jasper");
        //加载jasper文件创建inputStream
        FileInputStream isRef = new FileInputStream(resource.getFile());
        ServletOutputStream sosRef = response.getOutputStream();
        try {
            //创建JasperPrint对象
            JasperPrint jasperPrint = JasperFillManager.fillReport(isRef, new HashMap<>
                    (), new JREmptyDataSource());
            //写入pdf数据
            JasperExportManager.exportReportToPdfStream(jasperPrint, sosRef);
        } finally {
            sosRef.flush();
            sosRef.close();
        }
    }

    /**
     * 使用params数据
     * @param response  response
     * @param request  request
     * @throws Exception
     */
    @GetMapping("/testJasper2")
    public void createPdf2(HttpServletResponse response, HttpServletRequest
            request) throws Exception {
        //引入jasper文件。由JRXML模板编译生成的二进制文件，用于代码填充数据
        Resource resource = new ClassPathResource("templates/test_prameter.jasper");
        //加载jasper文件创建inputStream
        FileInputStream isRef = new FileInputStream(resource.getFile());
        ServletOutputStream sosRef = response.getOutputStream();
      Map<String,Object> param=new HashMap<>(8);
      param.put("userName","张三");
      param.put("company","XXXX");
      param.put("address","北京");
      param.put("mobile","1775555666");
      try {
            //创建JasperPrint对象
            JasperPrint jasperPrint = JasperFillManager.fillReport(isRef, param, new JREmptyDataSource());
            //写入pdf数据
            JasperExportManager.exportReportToPdfStream(jasperPrint, sosRef);
        } finally {
            sosRef.flush();
            sosRef.close();
        }
    }
    /**
     * 测试JDBC连接数据源
     * @param response  response
     * @param request  request
     * @throws Exception
     */
    @GetMapping("/testJasper03")
    public void createPdf3(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //1.引入jasper文件
        Resource resource = new ClassPathResource("templates/test_jdbc_datasource.jasper");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.创建JasperPrint,向jasper文件中填充数据
        ServletOutputStream os = response.getOutputStream();
        try {
            /**
             * 1.jasper文件流
             * 2.参数列表
             * 3.数据库连接
             */
            HashMap parameters = new HashMap();
            JasperPrint print = JasperFillManager.fillReport(fis,parameters,getConnection());
            //3.将JasperPrint已PDF的形式输出
            JasperExportManager.exportReportToPdfStream(print,os);
            response.setContentType("application/pdf");
        } catch (JRException e) {
            e.printStackTrace();
        }finally {
            os.flush();
        }
    }
    //创建数据库Connection
    public Connection getConnection() throws Exception {
        String url = "jdbc:mysql://127.0.0.1/employees";
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url, "root", "root");
        return conn;
    }
    //测试javaBean数据源
    @GetMapping("/testJasper04")
    public void createPdf4(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //1.引入jasper文件
        Resource resource = new ClassPathResource("templates/test_bean_datasource.jasper");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.创建JasperPrint,向jasper文件中填充数据
        ServletOutputStream os = response.getOutputStream();
        try {
            HashMap parameters = new HashMap();
            //构造javaBean数据源
            JRBeanCollectionDataSource ds = new
                    JRBeanCollectionDataSource(getUserList());
            /**
             * 1.jasper文件流
             * 2.参数列表
             * 3.JRBeanCollectionDataSource
             */
            JasperPrint print = JasperFillManager.fillReport(fis, parameters,ds);
            //3.将JasperPrint已PDF的形式输出
            JasperExportManager.exportReportToPdfStream(print,os);
            response.setContentType("application/pdf");
        } catch (JRException e) {
            e.printStackTrace();
        }finally {
            os.flush();
        }
    }

    /**
     * 测试分组
     * @param request request
     * @param response response
     * @throws Exception
     */
    @GetMapping("/testJasper05")
    public void testJasper05(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //1.引入jasper文件
        Resource resource = new ClassPathResource("templates/test_group.jasper");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.创建JasperPrint,向jasper文件中填充数据
        ServletOutputStream os = response.getOutputStream();
        try {
            HashMap parameters = new HashMap();
            //构造javaBean数据源
            JRBeanCollectionDataSource ds = new
                    JRBeanCollectionDataSource(getUserGroupList());
            /**
             * 1.jasper文件流
             * 2.参数列表
             * 3.JRBeanCollectionDataSource
             */
            JasperPrint print = JasperFillManager.fillReport(fis, parameters,ds);
            //3.将JasperPrint已PDF的形式输出
            JasperExportManager.exportReportToPdfStream(print,os);
            response.setContentType("application/pdf");
        } catch (JRException e) {
            e.printStackTrace();
        }finally {
            os.flush();
        }
    }
    //创建数据库Connection
    private List<User> getUserList() throws Exception {
        List<User> list = new ArrayList<>();
        Random random = new Random();

        for (int i=1;i<=1000;i++) {
            int num = random.nextInt(100);
            User user=new User("用户"+i,num);
            list.add(user);
        }
        return list;
    }

    private List<User> getUserGroupList() throws Exception {
        List<User> list = new ArrayList<>();
        Random random = new Random();

        for (int i=1;i<=100;i++) {
            if(i<40){
                User user=new User("用户"+i,random.nextInt(100),"公司1");
                list.add(user);
            }else {
                User user=new User("用户"+i,random.nextInt(100),"公司2");
                list.add(user);
            }

        }
        return list;
    }
}